﻿using System;
using CodeLibrary.Extensions.Common;

namespace CodeLibrary.Extensions
{
    public static class DateTimeExtensions
    {
        public static string ToWords(this TimeSpan val)
        {
            return TimeSpanArticulator.Articulate(val, TemporalGroupType.day
                | TemporalGroupType.hour
                | TemporalGroupType.minute
                | TemporalGroupType.month
                | TemporalGroupType.second
                | TemporalGroupType.week
                | TemporalGroupType.year);
        }
        
        public static DateTime MidNight(this DateTime val)
        {
            return new DateTime(val.Year, val.Month, val.Day, 0, 0, 0);
        }
        
        public static DateTime Noon(this DateTime val)
        {
            return new DateTime(val.Year, val.Month, val.Day, 12, 0, 0);
        }
        
        public static bool IsWithinRange(this DateTime val, DateTime floor, DateTime ceiling, bool includeBase)
        {
            if (floor > ceiling)
                throw new InvalidOperationException("floor value cannot be greater than ceiling value");
            if (floor == ceiling)
                throw new InvalidOperationException("floor value cannot be equal to ceiling value");

            if (includeBase)
                return (val >= floor && val <= ceiling);
            return (val > floor && val < ceiling);
        }
        
        public static TimeSpan GetTimeSpan(this DateTime val)
        {
            TimeSpan dateDiff;
            if (val < DateTime.Now)
                dateDiff = DateTime.Now.Subtract(val);
            else if (val > DateTime.Now)
                dateDiff = val.Subtract(DateTime.Now);
            else
                throw new InvalidOperationException("value cannot be equal to DateTime.Now");
            return dateDiff;
        }
    }
}
